package com.xiaotu.filter;

import com.alibaba.fastjson.JSONObject;
import com.xiaotu.constant.CommonConstants;
import com.xiaotu.util.R;
import com.xiaotu.util.TokenUtil;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 用户token验证
 *
 * @author zhangxiao
 * @create 2021-01-11 19:59
 */

public class UserTokenFilter extends OncePerRequestFilter {

    //private String[] exclusionFilter = {"/login","/uploadFile","/upload","/favicon.ico"};
    private String[] exclusionFilter = {"/"};

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String uri = request.getRequestURI();
        logger.debug("request uri:" + request.getRequestURI());
        logger.debug("request refer:" + request.getHeader("Referer"));
        logger.debug("request user-agent:" + request.getHeader("user-agent"));
        logger.debug("request token:" + request.getHeader("token"));
        logger.debug("request remoteHost:" + request.getRemoteHost());
        boolean isFilter = false;
        for (String e : exclusionFilter) {
            if (uri.indexOf(e) != -1) {
                isFilter = true;
            }
        }
        if (!isFilter) {
            boolean verifyToken = false;
            if (null != request.getHeader("token")) {
                logger.debug("验证是否携带：token");
                verifyToken = TokenUtil.verifyToken(TokenUtil.getCookie(request));
            }
            if (verifyToken) {
                logger.debug("验证token: success");
                filterChain.doFilter(request, response);
            } else {
                logger.debug("验证token: fail");
                response.setCharacterEncoding("UTF-8");
                response.setContentType("application/json; charset=utf-8");
                response.getWriter().append(JSONObject.toJSON(R.failed(CommonConstants.TOKENEXPIRED, "token verify fail or expired !")).toString());
            }
        } else {
            filterChain.doFilter(request, response);
        }
    }
}


